package com.study.juc.syncup;

import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.TimeUnit;

/**
 * @program: juc-study
 * @author: jzhou
 * @date: 2022-08-19 11:50
 * @version: 1.0
 * @description: 无锁 对象头内容展示
 **/
public class SynchronizedUpDemo {
	public static void main(String[] args) throws InterruptedException {
//		noLock();
//		演示偏向锁 需要开启 -XX:BiasedLockingStartupDelay=0 或睡4s以上
/*		TimeUnit.SECONDS.sleep(5);
		Object o = new Object();
		System.out.println("本应是偏向锁");
		System.out.println(ClassLayout.parseInstance(o).toPrintable());

		o.hashCode(); //没有重写一致性hash，重写后无效，当一个对象已经计算过identity hash code 他就无法进入偏向锁状态了
		synchronized (o){
			System.out.println("本应是偏向锁，但由于计算过一致性hash，直接升级为轻量锁");
			System.out.println(ClassLayout.parseInstance(o).toPrintable());
		}*/
		TimeUnit.SECONDS.sleep(5);
		Object o = new Object();
		System.out.println("本应是偏向锁");
		System.out.println(ClassLayout.parseInstance(o).toPrintable());

		synchronized (o){
			o.hashCode(); //没有重写一致性hash，重写后无效
			System.out.println("本应是偏向锁，但由于计算过一致性hash，直接升级为轻量锁");
			System.out.println(ClassLayout.parseInstance(o).toPrintable());
		}

	}

	private static void syncLock() {
		Object o = new Object();
		new Thread(() -> {
			synchronized (o){
				System.out.println(ClassLayout.parseInstance(o).toPrintable());
			}
		}).start();
		new Thread(() -> {
			synchronized (o){
				System.out.println(ClassLayout.parseInstance(o).toPrintable());
			}
		}).start();
	}


	private static void noLock() {
		Object o = new Object();

		System.out.println("10进制hash码："+o.hashCode());
		System.out.println("16进制hash码："+Integer.toHexString(o.hashCode()));
		//  1100111 01110011 00100111 10110110 hashcode 只需要31位
		// 01100111 01110011 00100111 10110110 把32位的最前面0拿掉刚好一致，最前面的0就像部位一样
		System.out.println("2进制hash码："+Integer.toBinaryString(o.hashCode()));

		System.out.println(ClassLayout.parseInstance(o).toPrintable());
	}
}
